package com.quectel.core.module.partybuildingtask.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.Week;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.partybuilding.PartyBuildingPlanConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingtask.dao.PartyBuildingPlanDao;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanDto;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanPersonBindingDto;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanTaskDto;
import com.quectel.core.module.partybuildingtask.entity.PartyBuildingPlanEntity;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanPersonBindingService;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanService;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanTaskService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:32
 */
@DubboService
public class PartyBuildingPlanServiceImpl implements PartyBuildingPlanService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyBuildingPlanServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_BUILDING_PLAN_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_BUILDING_PLAN_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyBuildingPlanDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_BUILDING_PLAN_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyBuildingPlanDao partyBuildingPlanDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyBuildingPlanPersonBindingService partyBuildingPlanPersonBindingService;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private PartyBuildingPlanTaskService partyBuildingPlanTaskService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_BUILDING_PLAN_LOCK + "#{#planId}"
            }
    )
    public void terminate(Long planId) {
        PartyBuildingPlanDto partyBuildingPlanDto = selectById(planId);
        if(partyBuildingPlanDto==null){
            return;
        }

        PartyBuildingPlanDto planDto =new PartyBuildingPlanDto();
        planDto.setId(partyBuildingPlanDto.getId());
        planDto.setEndTime(new Date());

        updateById(planDto);

        //查询所有的未完成的任务,删除
        Map<String,Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getPlanId),planDto.getId());
        params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecStatus),PartyBuildingPlanConstants.TaskStatus.UNCOMPLETED.getStatus());
        List<PartyBuildingPlanTaskDto> planTaskDtos = partyBuildingPlanTaskService.queryList(params);
        if(CollectionUtils.isNotEmpty(planTaskDtos)){
            for (PartyBuildingPlanTaskDto planTaskDto : planTaskDtos) {
                planTaskDto.setExecStatus(PartyBuildingPlanConstants.TaskStatus.CANCELED.getStatus());
                partyBuildingPlanTaskService.deleteById(planTaskDto.getId());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_BUILDING_PLAN_LOCK + "#{#planId}"
            }
    )
    public void cancel(Long planId) {
        PartyBuildingPlanDto partyBuildingPlanDto = selectById(planId);
        if(partyBuildingPlanDto==null){
            return;
        }
        PartyBuildingPlanDto planDto =new PartyBuildingPlanDto();
        planDto.setId(partyBuildingPlanDto.getId());
        planDto.setCancel(SystemConstants.YES);
        planDto.setEndTime(new Date());

        updateById(planDto);

        //查询所有的未完成的任务 标记为已取消
        Map<String,Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getPlanId),planDto.getId());
        params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecStatus),PartyBuildingPlanConstants.TaskStatus.UNCOMPLETED.getStatus());
        List<PartyBuildingPlanTaskDto> planTaskDtos = partyBuildingPlanTaskService.queryList(params);
        if(CollectionUtils.isNotEmpty(planTaskDtos)){
            for (PartyBuildingPlanTaskDto planTaskDto : planTaskDtos) {
                planTaskDto.setExecStatus(PartyBuildingPlanConstants.TaskStatus.CANCELED.getStatus());
                partyBuildingPlanTaskService.updateById(planTaskDto);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_BUILDING_PLAN_LOCK + "#{#partyBuildingPlanDto.id}"
            }
    )
    public Long saveOrUpdate(PartyBuildingPlanDto partyBuildingPlanDto) {
        if (partyBuildingPlanDto.getId() == null) {
            Long id = save(partyBuildingPlanDto);
            partyBuildingPlanDto.setId(id);
        } else {
            updateById(partyBuildingPlanDto);
        }

        // 删除绑定关系
        partyBuildingPlanPersonBindingService.deleteByPlanId(partyBuildingPlanDto.getId());

        // 绑定下党员信息到中间表
        for (PartyBuildingPlanPersonBindingDto partyBuildingPlanPersonBindingDto : partyBuildingPlanDto.getBindPerson()) {
            partyBuildingPlanPersonBindingDto.setPlanId(partyBuildingPlanDto.getId());
            partyBuildingPlanPersonBindingService.save(partyBuildingPlanPersonBindingDto);
        }

        //如果是单次任务 则直接生成
        if(PartyBuildingPlanConstants.PeriodType.SINGLE_TIME.getType().equals(partyBuildingPlanDto.getPeriodType())){
            //在任务开始那天

            CompletableFuture.runAsync(() -> {
                partyBuildingPlanTaskService.genTask(partyBuildingPlanDto, partyBuildingPlanDto.getStartTime());
            });

        }

        return partyBuildingPlanDto.getId();
    }
    

    @Override
    public PartyBuildingPlanDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_BUILDING_PLAN_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyBuildingPlanDto selectById(Long id){
            PartyBuildingPlanEntity entity = partyBuildingPlanDao.selectById(id);
        PartyBuildingPlanDto partyBuildingPlanDto = paddingField(CopyUtils.copyObj(entity, PartyBuildingPlanDto.class));

        return partyBuildingPlanDto;
    }

    @Override
    public List<PartyBuildingPlanDto> queryList(Map<String,Object> params){
        List<PartyBuildingPlanEntity> list = partyBuildingPlanDao.queryList(params);
        List<PartyBuildingPlanDto> result =  CopyUtils.copyList(list,PartyBuildingPlanDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyBuildingPlanDto paddingField(PartyBuildingPlanDto dto){
        if (dto != null){

            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            if(partyOrganizationDto!=null){
               dto.setPartyName(partyOrganizationDto.getName());
            }
            //任务状态 1未开始 2进行中 3已结束 4已取消
            if(SystemConstants.YES.equals(dto.getCancel())){
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.CANCELED.getStatus());
            }else if(DateTime.now().before(dto.getStartTime())){
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.NOT_BEGIN.getStatus());
            }else if(DateTime.now().after(dto.getEndTime())){
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.ENDED.getStatus());
            }else {
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.IN_PROGRESS.getStatus());
            }
            //时间处理
            dto.setPlanStartTime(DateUtils.format(dto.getStartTime(), DateUtils.FormatType.COMMON));
            String endTime = DateUtils.format(dto.getEndTime(), DateUtils.FormatType.COMMON);
            if(PartyBuildingPlanConstants.LONG_TERM_TIME.equals(endTime)){
                dto.setPlanEndTime(PartyBuildingPlanConstants.LONG_TERM_DESC);
            }else{
                dto.setPlanEndTime(endTime);
            }

            //periodValue
            if(PartyBuildingPlanConstants.PeriodType.WEEK.getType().equals(dto.getPeriodType())){
                List<String> strings = JacksonUtils.parseArray(dto.getPeriod(), String.class);
                StringBuilder  periodValue = new StringBuilder("每周");
                for (String string : strings) {
                    Week of = Week.of(Integer.parseInt(string));
                    periodValue.append(of.toChinese()).append(",");
                }

                periodValue.deleteCharAt(periodValue.length() - 1);
                dto.setPeriodValue(periodValue.toString());

            }else if(PartyBuildingPlanConstants.PeriodType.MONTH.getType().equals(dto.getPeriodType())){
                List<String> strings = JacksonUtils.parseArray(dto.getPeriod(), String.class);
                StringBuilder periodValue = new StringBuilder("每月");
                if(strings.get(0).equals(PartyBuildingPlanConstants.END_OF_MONTH_VALUE)){
                    periodValue.append("最后一天");
                }else{
                    periodValue.append(strings.get(0)).append("号");
                }
                dto.setPeriodValue(periodValue.toString());
            }else if(PartyBuildingPlanConstants.PeriodType.SINGLE_TIME.getType().equals(dto.getPeriodType())){
                dto.setPeriodValue("单次");
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyBuildingPlanDao.queryTotal(params);
    }

    @Override
    public Long save(PartyBuildingPlanDto dto){
        PartyBuildingPlanEntity entity = CopyUtils.copyObj(dto,PartyBuildingPlanEntity.class);
        entity.setId(Snowflake.nextId());
        partyBuildingPlanDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyBuildingPlanDto dto){
        PartyBuildingPlanEntity entity = CopyUtils.copyObj(dto,PartyBuildingPlanEntity.class);

        partyBuildingPlanDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyBuildingPlanDto dto) {
       PartyBuildingPlanEntity entity = CopyUtils.copyObj(dto,PartyBuildingPlanEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyBuildingPlanDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyBuildingPlanDao.deleteById(id);

        partyBuildingPlanPersonBindingService.deleteByPlanId(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
